<?php


namespace app\admin\controller;
use PHPExcel;

class Gong extends Common
{
//    public function index()
//    {
//        $gong_info = session('admin');
//        if ($gong_info['ro_id']==3){
//
//            if (input('get.list')) {
//                $this->map[] = ['b.or_num', 'like', '%' . input('get.list') . '%'];
//            }
//            if (input('get.us_tel')) {
//                $this->map[] = ['c.us_tel', 'like', '%' . input('get.us_tel') . '%'];
//            }
//            if (is_numeric(input('get.or_status'))) {
//                $this->map[] = ['b.or_status', '=', input('get.or_status')];
//            }
//            if (is_numeric(input('get.ca_id'))) {
//                $this->map[] = ['a.ca_id', '=', input('get.ca_id')];
//            }
//            if (input('get.start') && input('get.end') == "") {
//                $this->map[] = ['b.pay_time', '>=', input('get.start')];
//            }
//            if (input('get.start') == "" && input('get.end')) {
//                $this->map[] = ['b.pay_time', '<=', input('get.end')];
//            }
//            if (input('get.start') && input('get.end')) {
//                $this->map[] = ['b.pay_time', 'between', array(input('get.start'), input('get.end'))];
//            }
//
//            $this->map[] =['a.gong_id','=',$gong_info['id']];
//            $this->map[] =['b.or_status','<>',0];
//            $field = 'a.*, c.us_nickname, c.us_tel,b.pay_type,b.pay_time,b.or_num,b.or_status,d.addr_detail,d.addr_tel,d.addr_receiver';
//
//
//            $gongInfo = model('OrderDetail')
//                ->alias('a')
//                ->join('order b', 'a.or_id = b.id', 'LEFT')
//                ->join('user c', 'b.us_id = c.id', 'LEFT')
//                ->join('user_addr d', 'b.us_id = d.us_id', 'LEFT')
//                ->where($this->map)
//                ->field($field)
//                ->paginate(10, false, ['query' => request()->param()]);
//
//            foreach ($gongInfo as $k=>$v){
//                $gongInfo[$k]['send_addr']  = model('config')->where('key','addr_id')->value('value');
//            }
//            $this->assign('list',$gongInfo);
//            return $this->fetch();
//        }else{
//            $msg =  '请登录供货商账户进行查看';
//            $this->assign('msg',$msg);
//            return $this->fetch('null');
//        }
//
//    }


    public function index()
    {
        $gong_info = session('admin');
        if ($gong_info['ro_id']==3){

            if (input('get.list')) {
                $this->map[] = ['a.or_num', 'like', '%' . input('get.list') . '%'];
            }
            if (input('get.us_tel')) {
                $this->map[] = ['b.us_tel', 'like', '%' . input('get.us_tel') . '%'];
            }
            if (is_numeric(input('get.or_status'))) {
                $this->map[] = ['a.or_status', '=', input('get.or_status')];
            }
            if (is_numeric(input('get.ca_id'))) {
                $this->map[] = ['a.ca_id', '=', input('get.ca_id')];
            }
            if (input('get.start') && input('get.end') == "") {
                $this->map[] = ['a.pay_time', '>=', input('get.start')];
            }
            if (input('get.start') == "" && input('get.end')) {
                $this->map[] = ['a.pay_time', '<=', input('get.end')];
            }
            if (input('get.start') && input('get.end')) {
                $this->map[] = ['a.pay_time', 'between', array(input('get.start'), input('get.end'))];
            }

            $this->map[] =['a.gong_id','=',$gong_info['id']];
            $this->map[] =['a.or_status','<>',0];

            $field = 'a.*, b.us_nickname, b.us_tel,d.addr_detail,d.addr_tel,d.addr_receiver';

            $gongInfo = model('order')
                ->alias('a')
                ->join('user b', 'a.us_id = b.id', 'LEFT')
                ->join('user_addr d', 'a.us_id = d.us_id', 'LEFT')
                ->where($this->map)
                ->order('id desc')
                ->field($field)
                ->paginate(10, false, ['query' => request()->param()]);

//            halt($gongInfo);


//            $gongInfo = model('OrderDetail')
//                ->alias('a')
//                ->join('order b', 'a.or_id = b.id', 'LEFT')
//                ->join('user c', 'b.us_id = c.id', 'LEFT')
//                ->join('user_addr d', 'b.us_id = d.us_id', 'LEFT')
//                ->where($this->map)
//                ->field($field)
//                ->paginate(10, false, ['query' => request()->param()]);

            foreach ($gongInfo as $k=>$v){
                $gongInfo[$k]['send_addr']  = model('config')->where('key','addr_id')->value('value');
            }
//            halt($gongInfo);
            $this->assign('list',$gongInfo);
            return $this->fetch();
        }else{
            $msg =  '请登录供货商账户进行查看';
            $this->assign('msg',$msg);
            return $this->fetch('null');
        }

    }


    /**
     * 订单详情
     * @return mixed
     */
    public function detail($id)   // 订单id
    {
        $info = $this->getDetail($id);
        $this->assign($info);
        $this->assign('id',$id);
        return $this->fetch();
    }

    public function getDetail($id)
    {
//        $map['id'] = $id;
        $list = model('OrderDetail')
            ->where('or_id',$id)
            ->select();
//            ->detail($map);

//        halt($list);
//        foreach ($list as $k=>$v){
//           $or_id =  $v['or_id'];
//        }
        $addr_id = model('Order')->where('id',$id)->value('addr_id');
        $addr = model('UserAddr')->where('id',$addr_id)->find();
        $addr['addr_add'] = $addr['province'] . $addr['city'] . $addr['area'] . $addr['addr_detail'];

        return array(
            'list' => $list,
            'addr' => $addr,
        );
    }


    // 供货商提现
    public function tx(){

        $gong_info = session('admin');
        if ($gong_info['ro_id']==3){
            if ($this->is_post()) {
                $card_holder = input('post.card_holder'); //持卡人姓名
                $bank_name = input('post.bank_name');   // 开户行
                $bank_account = input('post.bank_account');    // 银行卡号
                $bank_branch_name = input('post.bank_branch_name');    // 银行分行名称
                $money = input('post.money');   //提现金额

                if (empty($card_holder)) {
                    return ['code' => 0, 'msg' => '持卡人姓名不能为空'];
                }
                if (empty($bank_name)) {
                    return ['code' => 0, 'msg' => '开户行不能为空'];
                }
                if (empty($bank_account)) {
                    return ['code' => 0, 'msg' => '银行卡号不能为空'];
                }
                if ( checkBankCard($bank_account)==false){
                    return ['code' => 0, 'msg' => '银行卡号不符合规则'];
                };
                if (empty($bank_branch_name)) {
                    return ['code' => 0, 'msg' => '银行分行名称不能为空'];
                }
                if (empty($money)) {
                    return ['code' => 0, 'msg' => '提现金额不能为空'];
                }
                if ($money<=0) {
                    return ['code' => 0, 'msg' => '提现金额不能小于等于0'];
                }
                $pay_money = $gong_info['gong_pay_money'];
                if ($money > $pay_money){
                    return ['code' => 0, 'msg' => '可提现金额不足'];
                }

                $tx =  model('admin')->where('id',$gong_info['id'])->setDec('gong_pay_money',$money);
                $gong_pay_money = model('admin')->where('id',$gong_info['id'])->value('gong_pay_money');  //供应商可用余额
                $gong_money = model('admin')->where('id',$gong_info['id'])->value('gong_money');  //供应商冻结余额



                $info = [
                    'us_id'=>$gong_info['id'],
                    'type'=>2,
                    'card_holder'=>$card_holder,
                    'bank_name'=>$bank_name,
                    'bank_account'=>$bank_account,
                    'bank_branch_name'=>$bank_branch_name,
                    'status'=>1,
                    'add_time'=>date('Y-m-d H:i:s')
                ];


                $bank = db('banks')->where('us_id',$gong_info['id'])->where('type',2)->select();
                if (empty($bank)){
                   $gongId =  db('banks')->insertGetId($info);

                }else{
                    db('banks')->where('us_id',$gong_info['id'])->where('type',2)->update($info);
                }
                $data = [
                    'type'=>3,
                    'us_id' => $gong_info['id'], //用户id
                    'y_pay_money'=>$gong_info['gong_pay_money'], //提现前可交易余额
                    'y_frozen_money'=>$gong_info['gong_money'],
                    'money' => $money, //提现金额
                    'over_pay_money'=>$gong_pay_money, // 提现后可用余额
                    'over_frozen_money'=>$gong_money, // 供应商冻结余额
                    'add_time' => date('Y-m-d H:i:s'), //申请时间
                    'tx_status' => 0, // 提现状态
                    'tx_people_role'=>2,  //1 用户提现  2 供应商提现
                    'explain'=>'供应商提现',
                    'tx_account_id'=>$gongId
                ];

                $in = db('money_detailed')->insert($data);
                if ($tx && $in){
                    return ['code'=>1,'msg'=>'已提交提现申请，等待审核'];
                }
            }

            $gong_pay_money = model('admin')->where('id',$gong_info['id'])->value('gong_pay_money');
            $dong_money = $gong_info['gong_money'];
            $banks = model('banks')->where('us_id',$gong_info['id'])->where('type',2)->find();

            $this->assign(['dong_money'=>$dong_money,'pay_money'=>$gong_pay_money,'banks'=>$banks]);
            return $this->fetch();

        }else{
            $msg =  '请登录供货商账户进行提现';
            $this->assign('msg',$msg);
            return $this->fetch('null');
        }
    }

    // 数据表格
    public function excel(){//导出Excel

        $gong_info = session('admin');
        $start = input('get.time_start');
        $end = input('get.time_send');
        $start_time = date("Y-m-d H:i:s",$start/1000);
        $end_time =$end!='NaN'? date("Y-m-d H:i:s",$end/1000):date('Y-m-d H:i:s');

        if (input('get.list')) {
            $this->map[] = ['a.or_num', 'like', '%' . input('get.list') . '%'];
        }
        if (input('get.us_tel')) {
            $this->map[] = ['b.us_tel', 'like', '%' . input('get.us_tel') . '%'];
        }
        if (is_numeric(input('get.or_status'))) {
            $this->map[] = ['a.or_status', '=', input('get.or_status')];
        }
        if (is_numeric(input('get.ca_id'))) {
            $this->map[] = ['a.ca_id', '=', input('get.ca_id')];
        }

        if (input('get.start') && input('get.end') == "") {
            $this->map[] = ['a.pay_time', '>=', $start_time];
        }
        if (input('get.start') == "" && input('get.end')) {
            $this->map[] = ['a.pay_time', '<=', $end_time];
        }
        if (input('get.start') && input('get.end')) {
            $this->map[] = ['a.pay_time', 'between', array($start_time, $end_time)];
        }

        $this->map[] =['a.gong_id','=',$gong_info['id']];
        $this->map[] =['a.or_status','<>',0];





        $field = 'a.*, b.us_nickname, b.us_tel,d.addr_detail,d.addr_tel,d.addr_receiver';

        $info = model('order')
            ->alias('a')
            ->join('user b', 'a.us_id = b.id', 'LEFT')
            ->join('user_addr d', 'a.us_id = d.us_id', 'LEFT')
            ->where($this->map)
            ->field($field)
            ->select();



//
//        $field = 'a.*, c.us_nickname, c.us_tel,b.pay_type,b.pay_time,b.or_num,b.or_status,d.addr_detail,d.addr_tel,d.addr_receiver';
//        $info = model('OrderDetail')
//            ->alias('a')
//            ->join('order b', 'a.or_id = b.id', 'LEFT')
//            ->join('user c', 'b.us_id = c.id', 'LEFT')
//            ->join('user_addr d', 'b.us_id = d.us_id', 'LEFT')
//            ->where($this->map)
//            ->field($field)
//            ->paginate(10, false, ['query' => request()->param()]);
        foreach ($info as $k=>$v){
            $info[$k]['send_addr']  = model('config')->where('key','addr_id')->value('value');
            $info[$k]['or_pd_name']  = '无限好平台商品';
        }

//       halt($info);
//        halt(Db::name('OrderDetail')->getLastSql());

        $xlsName  = "供货商订单详情";
        $xlsCell  = array(
            array('send_addr', '发货地址'),
            array('or_num', '订单号'),
            array('or_status', '订单状态'),

            array('or_pd_name', '商品名称'),

            array('addr_receiver', '收货人'),
            array('addr_tel', '电话'),
            array('addr_detail', '收货地址'),
        );

        $xlsData  = array();
        // halt($info['list']);
//        unset($info['list']['total']);
        foreach ($info as $k => $v) {
            $xlsData[$k]['or_num'] = $v['or_num'];
            if ($v['or_status'] == 1) {
                $xlsData[$k]['or_status'] = '待发货';
            } elseif ($v['or_status'] == 2) {
                $xlsData[$k]['or_status'] = '待收货';
            } elseif ($v['or_status'] == 3) {
                $xlsData[$k]['or_status'] = '已收货';
            } elseif ($v['or_status'] == 4) {
                $xlsData[$k]['or_status'] = '已取消';
            }else{
                $xlsData[$k]['or_status'] = '未发起支付';
            }

//            $xlsData[$k]['or_status'] = $v['or_status'];
            $xlsData[$k]['or_pd_name'] = $v['or_pd_name'];
//            $xlsData[$k]['or_pd_total'] = $v['or_pd_total'];
            $xlsData[$k]['addr_receiver'] = $v['addr_receiver'];
            $xlsData[$k]['addr_detail'] = $v['addr_detail'];
            $xlsData[$k]['addr_tel'] = $v['addr_tel'];
            $xlsData[$k]['send_addr'] = $v['send_addr'];
        }

        $this->exportExcel($xlsName,$xlsCell,$xlsData);

    }

    //发货
    public function deliver($id){
        $data = model('Order')
            ->where('id',$id)
            ->field('or_express,or_express_num,or_express_content')
            ->find();
        $this->assign([
            'id'=>$id,
            'data'=>$data
        ]);
        return $this->fetch();
    }

    public function shippingAddress()
    {

        if (is_post()) {
            $data = input('post.');
            $validate = validate('Verify');
            $rel = $validate->scene('deliver')->check($data);
            if (!$rel) {
                return['code'=>0,'msg'=>$validate->getError()];
            }
            $where['id'] = $data['or_id'];  // 订单详情id

            $or_status = model('order')->where($where)->value('or_status');


            // 更新物流信息
            if ($or_status ==2){
                $or_id = $data['or_id'];
                $data = [
                    'or_express'=>$data['or_express'],
                    'or_express_num' =>$data['or_express_num'],
                    'or_express_content' =>$data['or_express_content'],
                    'deliver_time'=> date('Y-m-d H:i:s')
                ];
                $updata = model('Order')->where('id',$or_id)->update($data);
                if ($updata){
                    //记录操作人信息

                    //操作订单统计
                    $recode_data = session('admin');

                    //订单号
                    $or_num = model('Order')->where('id',$or_id)->value('or_num');
                    $info = [
                        'admin_user_id'=>$recode_data['id'],
                        'edit_order_num'=>$or_num,
                        'admin_user_name'=>$recode_data['ad_name'],
                        'admin_user_phone'=>$recode_data['ad_tel'],
                        'admin_user_identity'=>$recode_data['ro_id'],
                        'type'=>1,
                        'edit_time'=>date('Y-m-d H:i:s'),
                        'content'=>'修改收货地址'
                    ];
                    model('Recording')->insert($info);
                    return ['code'=>1,'msg'=>'更新成功'];
                }

            }
            if($or_status != 1){
                return [
                    'code' => 0,
                    'msg' => '该订单不是待发货订单',
                ];
            }

            $or_id = $data['or_id'];
            $recode_data = session('admin');
            // 订单号
            $or_num = model('Order')->where('id',$or_id)->value('or_num');

            $info = [
                'admin_user_id'=>$recode_data['id'],
                'edit_order_num'=>$or_num,
                'admin_user_name'=>$recode_data['ad_name'],
                'admin_user_phone'=>$recode_data['ad_tel'],
                'admin_user_identity'=>$recode_data['ro_id'],
                'type'=>1,
                'edit_time'=>date('Y-m-d H:i:s'),
                'content'=>'添加收货地址'
            ];
//            halt($info);
//            $order_record = new OrderRecode;
            model('Recording')->insert($info);

            $data['or_status'] = 2;

            $data['deliver_time'] = date('Y-m-d H:i:s');

//            halt($data);

            $rst = model('Order')->save($data, $where);
            if ($rst) {
                return [
                    'code' => 1,
                    'msg' => '发货成功',
                ];
            }
            return [
                'code' => 0,
                'msg' => '发货失败',
            ];
        }


    }


    function exportExcel($expTitle,$expCellName,$expTableData){
        //include_once EXTEND_PATH.'PHPExcel/PHPExcel.php';//方法二
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName = $expTitle.date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        $num = $dataNum + 3;
        $objPHPExcel = new PHPExcel();//方法一
        //$objPHPExcel = new \PHPExcel();//方法二
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
        $objPHPExcel->getActiveSheet(0)->mergeCells('A'.$num.':'.$cellName[$cellNum-1].$num);//合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  表格生成时间:'.date('Y-m-d H:i:s'));
        // halt($num);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$num, '制表人:                      ' . '会计：                      ' . '出纳：                      ' . '审核：                      ');
        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]);
        }
        // Miscellaneous glyphs, UTF-8
        for($i=0;$i<$dataNum;$i++){
            for($j=0;$j<$cellNum;$j++){
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
            }
        }
        ob_end_clean();//这一步非常关键，用来清除缓冲区防止导出的excel乱码
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//"xls"参考下一条备注
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');//"Excel2007"生成2007版本的xlsx，"Excel5"生成2003版本的xls
        $objWriter->save('php://output');
        exit;
    }


}